import { ArticleApi } from '@/services/cms/CmsController';
import { PageContainer } from '@ant-design/pro-components';
import { Editor } from '@bytemd/react';
import { useLocation, useNavigate, useRequest } from '@umijs/max';
import { Button, message, Result, Space } from 'antd';
import { useState } from 'react';
import 'bytemd/dist/index.css'
import './index.css'
import 'github-markdown-css'
import gfm from '@bytemd/plugin-gfm'
import highlight from '@bytemd/plugin-highlight'
import Settings from './components/settings';
import { request, useSearchParams } from 'umi';
import 'highlight.js/styles/default.css'
import ResultWrap from '@/components/ResultWrap';

const plugins = [
    gfm(),
    highlight()
]
const HomePage: React.FC = () => {
    const navigate = useNavigate()
    let [search, setSearch] = useSearchParams()

    let id = search.get("id");

    let { loading, error, run: loadContent } = useRequest(() => id ? ArticleApi.fetch(id) : Promise.resolve({ content: "" }),
        {
            throwOnError: true,
            onSuccess(data, params) {
                setContent(data.content)
            },
        });

    let { run: save, loading: saveing } = useRequest((data) => id ? ArticleApi.update(id, data) : ArticleApi.create(data),
        {
            throwOnError: true,
            manual: true,
            onError() { message.error("保存失败") },
            onSuccess(data, params) {
                setSearch({ id: data.id + "" }, { replace: true })
                message.success("保存成功")
            },
        });

    let { run: publish } = useRequest(async () => {
        if (id) {
            await ArticleApi.update(id, { content });
            return ArticleApi.publish(id)
        } else {
            return Promise.reject("null id")
        }
    }, { manual: true, throwOnError: true, onError() { message.error("发布失败") }, onSuccess() { message.success("发布成功"), navigate(-1) }, })


    const [content, setContent] = useState('')
    const [showSetting, setShowSetting] = useState<number | String | null>(null)
    const [showIsNew, setShowIsNew] = useState<boolean>(false)

    return (
        <PageContainer ghost breadcrumbRender={false} loading={loading} header={{
            title: <Button onClick={() => navigate(-1)}>返回</Button>,
            extra: <Space>
                <Button loading={saveing} onClick={() => id ? save({ content }) : setShowIsNew(true)} >保存</Button>
                {id && <Button onClick={() => { setShowSetting(id) }}>设置</Button>}
                <Button color='primary' variant="outlined" onClick={() => id ? publish() : setShowIsNew(true)}>发布</Button>
            </Space>
        }}
        >
            <Settings id={showSetting} onFinish={(data) => data && setSearch({ id: data.id + "" }, { replace: true })} onClose={() => { setShowSetting(null); setShowIsNew(false) }} is_new={showIsNew} content={content}></Settings>
            <ResultWrap error={error} reload={loadContent}>
                <Editor
                    uploadImages={async (files) => {
                        let res = []
                        for (let i = 0; i < files.length; i++) {
                            const file = files[i];
                            let d = await request(`/file/upload/${file.name}`, { method: "POST", data: file })
                            res.push({ title: file.name, url: "/file" + d.url, alt: file.name })
                        }
                        return res
                    }}
                    value={content}
                    plugins={plugins}
                    onChange={(v) => { setContent(v) }}
                />
            </ResultWrap>
        </PageContainer>
    );
};

export default HomePage;
